import sys
import re
import fetion_exception
from sipc import SIPC_V2
from util import d_print, http_send

''' this is a fetion program used for personal service'''


FetionConfigURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx"
FetionConfigXML = """<config><user mobile-no="%s" /><client type="PC" version="3.2.0540" platform="W5.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /><client-config version="0" /></config>"""
STOCK_GROUP = '4'

TAG = 'Fetion2008'


class Fetion2008:
	def __init__(self, mobileno, passwd):
		self.__mobileno = mobileno
		self.__passwd = passwd
		self.__get_system_config()
		self.__set_system_config()
		self.login()
		print 'fetion instance is created and is to be logged'
	
	def login(self):
		self.__ssic, self.__domain = self.__ssi_login()
		self.__sipc_auth()
	
	def get_contact_list(self):
		response = self.__SIPC.get_contact_list()
		pattern_fetionuri = r'uri="(.*?)" user-id=.*?buddy-lists="(.*?)"' #not greedy
		pattern_fetionid = r'uri="sip:(.*?)@fetion.com.cn'
		ids = re.findall(pattern_fetionid, response)
		uris_buddylist = re.findall(pattern_fetionuri, response)
		
		uris, ids = self.__filter(uris_buddylist, ids)
		
		d_print(TAG, msg = 'Friend fetion uri list in stock_service group\n')
		print uris
		
		d_print(TAG, msg = 'Friend fetion id list in stock_service group\n')
		print ids
		
		return (uris, ids)
	
	def get_contact_info(self, uri):
		pattern_mobile = r'mobile-no="(.*?)"'
		response = self.__SIPC.get_contact_info(uri)
		match = re.search(pattern_mobile, response)
		if match: #if the other side doesn't confirm your invitation
			print match.group(1)
			mobile_no = match.group(1)
		return mobile_no
	
	def add_buddy(self, type, who):
		assert type == 'mobile' or type == 'fetion'
		self.__SIPC.add_buddy(type, who) #todo: check code (eg:486: servier is busy, exceed the maximum for addbuddy per day)
	def send_sms(self, sms, to=None):
		if not to:
			self.__SIPC.send_sms(self.__uri, sms, 'SENDCatSMS')
		else:
			self.__SIPC.send_sms(to, sms) #to should be uri

	def __get_system_config(self):
		global FetionConfigURL
		global FetionConfigXML
		url = FetionConfigURL
		body = FetionConfigXML % self.__mobileno
		d_print(TAG, ('url',), locals())
		d_print(TAG, ('body',), locals())
		self.__config_data = http_send(url,body).read()
	
	def __set_system_config(self):
	    sipc_url = re.search("<ssi-app-sign-in>(.*)</ssi-app-sign-in>",self.__config_data).group(1)
	    sipc_proxy = re.search("<sipc-proxy>(.*)</sipc-proxy>",self.__config_data).group(1)
	    http_tunnel = re.search("<http-tunnel>(.*)</http-tunnel>",self.__config_data).group(1)
	    d_print(TAG, ('sipc_url','sipc_proxy','http_tunnel'),locals())
	    self.__sipc_url   = sipc_url
	    self.__sipc_proxy = sipc_proxy
	    self.__http_tunnel= http_tunnel
	
	def __ssi_login(self):
		url = self.__sipc_url + "?mobileno="+self.__mobileno+"&pwd="+self.__passwd
		d_print(TAG, ('url',), locals())
		try:
			ret =  http_send(url, login = True)
		except FetionException, e:
			print e.show_error()
			sys.exit(-1)
		
		if ret:
			header = str(ret.info())
			body   = ret.read()
			ssic = re.search("ssic=(.*);",header).group(1)
			sid  = re.search("sip:(.*)@",body).group(1)
			uri  = re.search('uri="(.*)" mobile-no',body).group(1)
			status = re.search('user-status="(\d+)"',body).group(1)
			domain = "fetion.com.cn"
			d_print(TAG, ('ssic','sid','uri','status','domain'),locals(),"Get SID OK")
			self.__sid = sid
			self.__uri = uri
			return (ssic,domain)
		else:
			return (None, None)

	def __sipc_auth(self):
		self.__SIPC = SIPC_V2(self.__sid, self.__domain, self.__passwd, self.__http_tunnel, self.__ssic, self.__sipc_proxy)
		self.__SIPC.register()
	
	def __filter(self, uris_buddylist, ids):
		assert len(uris_buddylist) == len(ids)
		global STOCK_GROUP
		uris_stock = []
		ids_stock = []
		buddy_num = len(uris_buddylist)
		for i in range(buddy_num):
			if uris_buddylist[i][1] == STOCK_GROUP:
				uris_stock.append(uris_buddylist[i][0])
				ids_stock.append(ids[i])
		return uris_stock, ids_stock

def testcase_2008():
	fetion = Fetion2008('13601804916', 'sj19840615')
	uri_list = fetion.get_contact_list()[0]
	mobile_no_list = []
	for uri in uri_list:
		mobile_no = fetion.get_contact_info(uri)
		mobile_no_list.append(mobile_no)
	
	fetion.send_sms('this is a test msg send to peter')
	#fetion.add_buddy('mobile', '13661576824') #gary
	#fetion.add_buddy('mobile', '13585974136') #ricky
	#fetion.add_buddy('mobile', '13758193432') #zhang zhi qiang

if __name__ == '__main__':
	testcase_2008()
